<template>
  <!--弹框添加标签-->
  <a-modal
    title="添加标签"
    :visible="visible"
    placement="right"
    @ok="handleOk"
    @cancel="closeDrawer"
  >
    <a-form-model ref="modalForm" :model="modalForm" :rules="modalRules">
      <a-form-model-item label="标签名称" prop="labelName">
        <a-input v-model="modalForm.labelName" :maxLength="10"></a-input>
      </a-form-model-item>
      <a-form-model-item label="适用于" prop="referTo">
        <a-select v-model="modalForm.referTo">
          <a-select-option :key="refer.id" v-for="refer in referToList">
            {{ refer.referName }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="标签描述" prop="labelDesc">
        <a-input v-model="modalForm.labelDesc"></a-input>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import {
  saveLabel,
  querySingleLabel,
  updateSingleLabel,
} from "../../../api/label";

export default {
  name: "AddLabel",
  data() {
    return {
      modalForm: {
        labelName: "",
        referTo: "1",
        labelDesc: "",
      },
      modalRules: {
        labelName: [
          { required: true, message: "请填写标签名称", trigger: "blur" },
        ],
        referTo: [
          { required: true, message: "请选择适用对象", trigger: "blur" },
        ],
      },
      visible: false,
      referToList: [{ id: "1", referName: "电站" }], //国家列表
      id: "",
    };
  },
  props: {
    currentData: {
      type: Object,
      default: () => {},
    },
  },
  watch: {
    currentData(newv) {
      if (newv.id) {
        this.modalForm.labelName = newv.labelName;
        this.id = newv.id;
        this.modalForm.labelDesc = newv.labelDesc;
      } else {
        this.modalForm.labelName = "";
        this.id = "";
        this.modalForm.labelDesc = "";
      }
    },
  },
  methods: {
    getShow(show) {
      this.visible = show;
    },
    handleOk() {
      this.$refs.modalForm.validate((valid) => {
        if (valid) {
          if (this.id) {
            updateSingleLabel({ id: this.id, ...this.modalForm }).then(
              (res) => {
                this.visible = false;
                console.log("----------");
              }
            );
          } else {
            saveLabel(this.modalForm)
              .then((res) => {
                console.log(res);
                this.visible = false;
              })
              .catch(() => {
                this.$message.error({
                  content: "添加标签失败",
                });
              });
          }
          this.$emit("update");
        }
      });
    },
    closeDrawer() {
      this.visible = false;
    },
  },
};
</script>

<style scoped>
</style>
